import re

import requests

from stealer import config
from . import BaseAdapter

headers = {
    "accept": "*/*",
    "accept-encoding": "gzip, deflate",
    "user-agent": config.USER_AGENT
}

share_headers = {
    "accept": "*/*",
    "accept-encoding": "gzip, deflate",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-origin",
    "user-agent": config.USER_AGENT
}

download_headers = {
    "accept": "*/*",
    "accept-encoding": "identity;q=1, *;q=0",
    "range": "bytes=0-",
    "sec-fetch-dest": "video",
    "sec-fetch-mode": "no-cors",
    "sec-fetch-site": "cross-sit",
    "user-agent": config.USER_AGENT
}


class PiPiXiaBaseAdapter(BaseAdapter):
    prefix = r'h5\.pipix\.com/s\/'

    @classmethod
    def get_prefix_pattern(cls) -> str:
        return 'h5\.pipix\.com/s\/'

    @classmethod
    def make_url(cls, index) -> str:
        return f'http://h5.pipix.com/s/{index}'

    def index(self, url):
        index = re.findall(r'(?<=s\/)\w+', url)

        try:
            return index[0]
        except ValueError:
            return None

    def parse(self, url=None, header: bool = True):
        res = requests.get(url, headers=headers)

        try:
            id = re.findall(r"(?<=item\/)(\d+)(?=\?)", res.url)[0]
        except ValueError:
            return res.reason

        url = f"https://h5.pipix.com/bds/webapi/item/detail/?item_id={id}&source=share"
        res = requests.get(url, headers=share_headers)
        res = res.json()

        try:
            link = res['data']['item']['comments'][0]['item']['video']['video_high']['url_list'][0]['url']
        except (KeyError, IndexError) as e:
            raise e

        data = {
            'link': link,
            'name': 'name',
            'meta': {
                'headers': download_headers
            }}
        return data


if __name__ == '__main__':
    PiPiXiaBaseAdapter().fetch('http://h5.pipix.com/s/3asShh')
